package com.example.turnoverwarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.turnoverwarning.dto.PageResult;
import com.example.turnoverwarning.entity.Order;
import com.example.turnoverwarning.entity.Shop;
import com.example.turnoverwarning.exception.BusinessException;
import com.example.turnoverwarning.mapper.OrderMapper;
import com.example.turnoverwarning.mapper.ShopMapper;
import com.example.turnoverwarning.service.ShopService;
import com.example.turnoverwarning.vo.OrderVO;
import com.example.turnoverwarning.vo.ShopDetailVO;
import com.example.turnoverwarning.vo.ShopVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Survive
 * @date 2025/3/11
 * @description TODO
 */
@Service
@AllArgsConstructor
public class ShopServiceImpl implements ShopService {

    private OrderMapper orderMapper;

    private  ShopMapper shopMapper;

    @Override
    @Transactional
    public void addShopAlert(Long shopId, String mail, BigDecimal threshold) {
        // 1. 校验店铺存在性
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }
        // 2. 更新字段
        shop.setMail(mail);
        shop.setThreshold(threshold);

        // 3. 持久化到数据库
        int rows = shopMapper.updateById(shop);
    }

    @Override
    @Transactional
    public Shop updateShopAlert(Long id, String mail, BigDecimal threshold) {
        // 1. 验证店铺存在性
        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }

        // 2. 数据更新
        shop.setMail(mail);
        shop.setThreshold(threshold);
        shop.setUpdateTime(LocalDateTime.now()); // 更新时间戳

        int rows = shopMapper.updateById(shop);

        return shop;
    }

    @Override
    @Transactional
    public Shop clearAlertConfig(Long shopId) {
        // 1. 验证店铺存在性
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }

        // 2. 清除预警配置
        shop.setMail("");          // 清空邮箱
        shop.setThreshold(BigDecimal.ZERO);  // 重置阈值
        shop.setUpdateTime(LocalDateTime.now());
        int rows = shopMapper.updateById(shop);
        return shop;
    }

    @Override
    public PageResult<ShopVO> listShops(Integer page, Integer size, String name) {
        // 1. 构建分页参数
        Page<Shop> pageParam = new Page<>(page, size);

        // 2. 构建查询条件
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(name), Shop::getName, name)
                .select(Shop::getId, Shop::getName, Shop::getMail,
                        Shop::getThreshold, Shop::getUpdateTime);

        // 3. 执行分页查询
        Page<Shop> shopPage = shopMapper.selectPage(pageParam, wrapper);

        // 4. 转换VO对象
        List<ShopVO> vos = shopPage.getRecords().stream()
                .map(shop -> new ShopVO(
                        shop.getId(),
                        shop.getName(),
                        shop.getMail(),
                        shop.getThreshold(),
                        shop.getUpdateTime()
                ))
                .collect(Collectors.toList());

        // 5. 封装分页结果
        return new PageResult<>(
                shopPage.getCurrent(),
                shopPage.getSize(),
                shopPage.getTotal(),
                vos
        );
    }

    @Override
    public ShopDetailVO getShopDetail(Long shopId, Boolean withOrders) {
        // 1. 查询基础信息
        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }

        // 2. 构建VO对象
        ShopDetailVO vo = new ShopDetailVO()
                .setId(shop.getId())
                .setName(shop.getName())
                .setMail(shop.getMail())
                .setThreshold(shop.getThreshold())
//                .setCreateTime(shop.getCreateTime())
                .setUpdateTime(shop.getUpdateTime());

        // 3. 查询当日订单（按需加载）
        if (Boolean.TRUE.equals(withOrders)) {
            List<Order> orders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .eq(Order::getShopId, shopId)
                            .ge(Order::getCreateTime, LocalDate.now().atStartOfDay())
            );
            vo.setOrdersToday(convertToOrderVO(orders));
        }

        return vo;
    }

    private List<OrderVO> convertToOrderVO(List<Order> orders) {
        return orders.stream()
                .map(o -> new OrderVO(o.getId(), o.getAmount(), o.getCreateTime()))
                .collect(Collectors.toList());
    }

}
